from nmj.scanners.movie import NMJMovie
from nmj.sqlite.nmj_db import NMJ_MOVIE_TYPE
from urllib import urlencode
from urllib2 import urlopen
import json
import pprint

class AllocineMovie(NMJMovie):
	def __init__(self, title, synopsis="", short_synopsis="", posters=None, fanarts=None,
			genres=None, cast=None, show_type=NMJ_MOVIE_TYPE, rating=0.0):
		NMJMovie.__init__(self, title, synopsis=synopsis, short_synopsis=short_synopsis,
			posters=posters, fanarts=fanarts, genres=genres, cast=cast, show_type=show_type, rating=rating)

class AlloCineScanner(object):
	def __init__(self):
		self.domain = "api.allocine.fr"
		self.format_string = "%s"

	@property
	def search_url(self):
		domain = self.domain.strip('/')
		return "http://%s/xml/search?%%s" % domain

	@property
	def movie_url(self):
		domain = self.domain.strip('/')
		return "http://%s/xml/movie?%%s" % domain

	def search(self, string, **kwargs):
		params = {
			'q': self.format_string % string,
			'partner' : 8,
			'json': 1,
		}

		url = self.search_url % urlencode(params)
		page = urlopen(url)
		return json.load(page)

	def _json2movie(self, json):
		#pprint.pprint(json)
		movie = json["movie"]
		return AllocineMovie(
			movie["title"],
			movie["synopsis"],
			movie["synopsisShort"],
			posters=None,
			fanarts=None,
			genres=[genre["$"] for genre in movie.get("genre", [])],
		)

	def get_media(self, movie_id):
		params = {
			'code': movie_id,
			'partner' : 8,
			'json': 1,
			"profile" : "large",
		}

		url = self.movie_url % urlencode(params)
		page = urlopen(url)
		return self._json2movie(json.load(page))

if __name__ == "__main__":
	webapi = AlloCineScanner()
	result = webapi.search("avatar")
	movies = result["feed"]["movie"]
	print "Found %d results" % len(movies)
	pprint.pprint(set([m["class"] for m in movies[0]["movie"]["media"]]))
#	pprint.pprint(movies[0])
#	movie = webapi.get_media(movies[0]["code"])
#	pprint.pprint(movie)


